import axios from 'axios'
import router from '../router'
import { Message } from 'view-design'
import Cookies from 'js-cookie'
import { getToken } from '@/libs/util'
import store from '@/store'

// eslint-disable-next-line no-unused-vars
const tipSuccess = msg => {
  Message.success(msg)
}

const tipError = msg => {
  Message.error(msg)
}

const toLogin = () => {
  router.replace({
    path: '/login',
    query: {
      redirect: router.currentRoute.fullPath
    }
  })
}

const errorHandle = (status, other) => {
  // 状态码判断
  switch (status) {
    // 401: 未登录状态，跳转登录页
    case 401:
      toLogin()
      break
    // 403 token过期
    // 清除token并跳转登录页
    case 403:
      tipError('登录过期，请重新登录')
      localStorage.removeItem('token')
      setTimeout(() => {
        toLogin()
      }, 1000)
      break
    // 404请求不存在
    case 404:
      tipError('请求的资源不存在')
      break
    default:
      tipError('系统内部错误，请稍后重试')
  }
}
let instance = axios.create({
  timeout: 1000 * 10
})
// 设置token
instance.defaults.headers.token = Cookies.get('token')
instance.defaults.headers.source = 'pc'
instance.interceptors.request.use(
  config => {
    const token = getToken()
    if (!token) {
      toLogin()
      Promise.reject('token不存在')
    }
    store.dispatch('SetLoading', true)
    config.headers['token'] = token
    config.headers['Cache-Control'] = 'no-cache'
    config.headers['Pragma'] = 'no-cache'
    return config
  },
  error => {
    setTimeout(function() {
      store.dispatch('SetLoading', 0)
    }, 300)
    Promise.error(error)
  }
)
instance.interceptors.response.use(
  response => {
    store.dispatch('SetLoading', false)
    if (200 === response.status) {
      if (401 === response.data.code) {
        tipError(response.data.message)
        toLogin()
      } else {
        return Promise.resolve(response.data)
      }
    } else {
      return Promise.reject(response.data)
    }
  },
  error => {
    store.dispatch('SetLoading', false)
    const { response } = error
    if (response) {
      errorHandle(response.code, response.data.Message)
      return Promise.reject(response)
    } else {
      if (!window.navigator.onLine) {
        tipError('断网了，请检查您的网络连接')
      } else {
        return Promise.reject(error)
      }
    }
  }
)

export default instance
